//
//  YBSSEManager.swift
//  Moonlight
//
//  Created by 清风徐来 on 2023/7/4.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit

class YBSSEManager {

    // 私有化init方法（只能通过sharedInstance()方法创建）
    private init() { }
    
    private static var _sharedInstance: YBSSEManager?
    
    class func sharedInstance() -> YBSSEManager {
        guard let instance = _sharedInstance else {
            _sharedInstance = YBSSEManager()
            return _sharedInstance!
        }
        return instance
    }
    
    /// 销毁单例对象
    class func destroy() {
        _sharedInstance = nil
    }
    
    var sse_source: EventSource?
    
    // 开始链接
    func func__startWithEventSource() {
        let sse_string = NetApiPort.ApiMainUrl + "/app/sse/connect/" + AppHelper.kUserId
        print("SSE - 准备连接 - \(sse_string)")
        
        let source = EventSource.init(url: URL(string: sse_string))
        source?.onReadyStateChanged({ event in
            print("SSE - 连接状态改变 - \(String(describing: event?.readyState))")
        })
        
        source?.onMessage({ event in
            print("SSE - 收到消息 - \(String(describing: event))")
      
            if let jsonData = event?.data.data(using: .utf8) {
                do {
                    let decoder = JSONDecoder()
                    let message = try decoder.decode(Message.self, from: jsonData)
                    
                    print("Title: \(message.title)")
                    print("Content: \(message.content)")
                    print("Scope: \(message.scope)")
                    print("Target: \(message.target)")
                    
                    var notiMessage = ""
                    // 通知
                    if message.content == "DOWN" {
                        notiMessage = "关机成功"
                        NotificationCenter.default.post(name: .didPowerOffSuccess, object: nil)
                    }else {
                        notiMessage = "开机成功"
                        NotificationCenter.default.post(name: .didPowerOnSuccess, object: nil)
                    }
                    
                    // 测试
                    DispatchQueue.main.async {
                        HintTool.toast(notiMessage)
                    }
                    
                } catch {
                    print("Error decoding JSON: \(error)")
                }
            } else {
                print("Invalid JSON string")
            }
        })
        
        self.sse_source = source
    }
    
    // 关闭SSE
    func func__endWithEventSource() {
        if let sse_source {
            sse_source.close()
        }
    }
    
}

struct Message: Codable {
    let title: String
    let content: String
    let scope: String
    let target: String
}

// 通知
extension Notification.Name {
    static let didPowerOnSuccess = Self("DID_POWERON_SUCCESS_NOTIFICATION")        // 开机成功
    static let didPowerOffSuccess = Self("DID_POWEROFF_SUCCESS_NOTIFICATION")        // 关机成功
}

